package com.example.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.annotation.Roles;
import com.example.demo.context.BaseContext;
import com.example.demo.dto.PageDTO;
import com.example.demo.dto.UserAddDTO;
import com.example.demo.dto.UserLoginDTO;
import com.example.demo.dto.UserUpdateDTO;
import com.example.demo.exception.UserAddException;
import com.example.demo.exception.UserLoginException;
import com.example.demo.mapper.UserMapper;
import com.example.demo.pojo.User;
import com.example.demo.pojo.UserRole;
import com.example.demo.service.UserRoleService;
import com.example.demo.service.UserService;
import com.example.demo.utils.JwtUtil;
import com.example.demo.utils.RedisIdWorker;
import com.example.demo.utils.RegexUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private UserRoleService userRoleService;
    @Override
    public void addUser(UserAddDTO userDTO) {
        String vCode = userDTO.getVCode();
        String password = userDTO.getPassword();

        if (StrUtil.isBlank(password) || StrUtil.isBlank(vCode) ||
        StrUtil.isBlank(userDTO.getTelephone()) || StrUtil.isBlank(userDTO.getEmail())) {
            throw new UserAddException("创建用户存在空字段");
        }
//        if (!RegexUtils.isCodeInvalid(vCode)) {
//            throw new UserAddException("验证码格式错误");
//        } else if (!RegexUtils.isPhoneInvalid(userDTO.getTelephone())) {
//            throw new UserAddException("手机号格式错误");
//        } else if (!RegexUtils.isEmailInvalid(userDTO.getEmail())) {
//            throw new UserLoginException("邮箱格式错误");
//        }

        // TODO 判断vCode时候合规 根据vcode 和 telephone 在redis中查询相关结果


        // 对密码进行一个加密(md5)
        password = SecureUtil.md5(password);

        // 生成用户 添加到数据库
        User user = BeanUtil.copyProperties(userDTO, User.class);
        user.setId(redisIdWorker.nextId("user"));
        user.setPassword(password);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        save(user);

    }

    @Override
    @Transactional
    public String loginUser(UserLoginDTO userLoginDTO) {
        String password = userLoginDTO.getPassword();
        String telephone = userLoginDTO.getTelephone();
        if (StrUtil.isBlank(password) || StrUtil.isBlank(telephone)) {
            throw new UserLoginException("存在字段为空");
        }
        // 在数据库中根据telephone 和 password 查找 记录
        password = SecureUtil.md5(password);

        User user = lambdaQuery()
                .eq(User::getTelephone, telephone)
                .eq(User::getPassword, password)
                .one();

        if (user == null) {
            throw new UserLoginException("用户没有注册或密码错误");
        }
        // 生成jwt
        // TODO 为jwt设置过期时间 拦截并验证token
        // 登录成功放回jwt
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());

        return JwtUtil.createJWT(
                "yangqi",
                7200000000000L,
                claims);
    }

    @Override
    public List<User> getUserBC(PageDTO pageDTO) {
        Integer page = pageDTO.getPage();
        Integer pageSize = pageDTO.getPageSize();
        String sortFiled = pageDTO.getSortFiled();

        Page<User> p = Page.of(page, pageSize);
        p.addOrder(new OrderItem("id", false));
        lambdaQuery().page(p);
        return p.getRecords();
    }

    @Override
    public List<User> getUserC(PageDTO pageDTO) {
        Long id = BaseContext.getCurrentId();

        Integer page = pageDTO.getPage();
        Integer pageSize = pageDTO.getPageSize();
        String sortFiled = pageDTO.getSortFiled();

        Page<User> p = Page.of(page, pageSize);
        p.addOrder(new OrderItem("id", false));
        lambdaQuery().eq(User::getSuperiorId, id).page(p);

        return p.getRecords();
    }

    @Override
    @Transactional
    public void updateUser(UserUpdateDTO userDTO) {
        // 目前每个user 只有 一个 role 所以逻辑得到简化

        // 判断当前节点连在哪层
        int roles = 0;
        User s = lambdaQuery().eq(User::getId, userDTO.getSuperiorId()).one();
        if (s.getSuperiorId() == null) roles = 2;
        else roles = 3;
        // 建立新边
        // 找到之前的边 将其删除
        userRoleService.lambdaUpdate().set(UserRole::getRoleId, roles).eq(UserRole::getUserId, userDTO.getId()).update();
        // 修改权限
        lambdaUpdate().set(User::getSuperiorId, userDTO.getSuperiorId()).eq(User::getId, userDTO.getId()).update();

    }

    @Override
    public User getUserById(Long id) {
        return getById(id);
    }



}
